package cn.edu.guet.day01;

/*
 * 题目：子线程循环10次，接着主线程循环100次，接着又回到子线程循环10次，
 *     接着在回到主线程又循环100次，如此循环50次。
 * 
 * 经验：要用到的共同数据（包括同步锁）或共同算法的若干个方法应该归在同一个类身上，这种设计
 * 	         正好体现了高内聚和程序的健壮性。
 * 
 * */

public class TraditionalThreadComunication {

	public static void main(String[] args) {
		final Business bussiness = new Business();
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i <= 50; i++) {
					bussiness.sub(i);
				}
			}
		}).start();

		for (int i = 1; i <= 50; i++) {
			bussiness.main(i);
		}
	}
} 

class Business {
	private boolean bShouldSub = true;
	
	public synchronized void sub(int i) {
		//while比if更健壮，while可以防止spurious wakeup（伪唤醒）
		while(!bShouldSub){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int j = 1; j <= 10; j++) {
			System.out.println("sub thread sequec of " + j + " loop of " + i);
		}
		bShouldSub = false;
		//唤醒主线程
		this.notify();
	}

	public synchronized void main(int i) {
		while(bShouldSub){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int j = 1; j <= 100; j++) {
			System.out.println("main thread sequec of " + j + " loop of " + i);
		}
		bShouldSub = true;
		//唤醒子线程
		this.notify();
	}
}
